/**
 * Copyright (C), 2020-2020, 软件公司
 * FileName: RabbitProducer.java
 * Author:   cakin
 * Date:     2020/5/2
 * Description: 生产者
 */
package com.rabbitmq.simple;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;
import com.rabbitmq.util.ConnectionUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 生产者
 */
@Slf4j
public class RabbitProducer {
    /**
     * 交换器
     * 不需要在RabbitMQ中创建，程序帮我们创建了
     */
    private static final String EXCHANGE_NAME = "exchange_demo2";
    /**
     * 绑定键
     * 不需要在RabbitMQ中创建，程序帮我们创建了
     */
    private static final String ROUTING_KEY = "routingkey_demo2";
    /**
     * 队列
     * 不需要在RabbitMQ中创建，程序帮我们创建了
     */
    private static final String QUEUE_NAME = "queue_demo2";
    /**
     * IP地址
     */
    private static final String IP_ADDRESS = "127.0.0.1";


    public static void main( String[] args ) {

//        Connection connection = ConnectionUtils.getConnection(IP_ADDRESS, PORT, "/vhost_xyn","user_xyn", "123456");
        // 实例化一个连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(IP_ADDRESS);
        // 在RabbitMQ中要先创建用户名和密码
        factory.setUsername("root");
        factory.setPassword("123456");
        try {
            // 实例化一个连接
            Connection connection = factory.newConnection();
            // 实例化一个信道
            Channel channel = connection.createChannel();
            // 创建一个 type="direct" 、持久化的、非自动删除的交换器
            channel.exchangeDeclare(EXCHANGE_NAME, "direct", true, false, null);
            // 创建一个持久化、非排他的、非自动删除的队列
            channel.queueDeclare(QUEUE_NAME, true, false, false, null);
            // 将交换器与队列通过路由键绑定，这个地方的ROUTING_KEY是binding key
            channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY);
            // 发送一条持久化的消息: hello world !
            String message = "Hello World !";
            // 消息发布，这个地方的ROUTING_KEY是routing key，当binding key和routing key匹配时，队列才会收到
            channel.basicPublish(EXCHANGE_NAME, ROUTING_KEY,
                    MessageProperties.PERSISTENT_TEXT_PLAIN,
                    message.getBytes());
            //关闭资源
            ConnectionUtils.close(channel, connection);
        } catch (IOException e) {
            log.info("catch IOException");
        } catch (TimeoutException e) {
            log.info("catch TimeoutException");
        }
    }
}
